<html>
    <head>
        <meta charset="UTF-8">
        <style>
            div{
                text-align:center;
            }
        </style>
    </head>
    <body onload=todolist('0')>
           <h1>待办事项清单</h1>

           <input type="text" id='list' placeholder="添加新事项">
           <input type='submit' value="+" onclick=submit()><br/><br/>
           <input type="text" placeholder="删除事项" id="del">
           <input type="submit" value="删除" onclick=del_todo()><br/><br/>
           <input type="submit" onclick=todolist('1') value="已完成事项" >
            <input type="submit" onclick=todolist('0') value="未完成事项">
            <input type="submit" onclick=todolist('all') value="全部事项"><br/>
           <ul id="a">


           </ul>
       </body>


    <script>
       //展示待办事项
       function todolist(completed){
            fetch('/todos'+'?completed='+completed)
                .then(res=>res.json())
                .then(data=>{
                        document.getElementById("a").innerHTML='';
                        var operation=data.todos
                        for(var i=0;i<operation.length;i++){
                        var opt='<li><input type="checkbox" name="'+operation[i].id+'"onchange="is_finish(this.name)"><span>'+operation[i].title+'</span></li>'
                        document.getElementById('a').innerHTML+=opt;

                            }})
                            }
                            
       //添加待办事项
       function submit(){
            var url='/todos'
            var headers={
                'Content-Type':'application/x-www-form-urlencoded'
            }
            var value=document.getElementById("list").value
            fetch(url,{
                method:"POST",
                body:"title="+value,
                headers:headers})
               .then(res=>res.json())
               .catch(error=>console.error("Error:",error))
               .then(function(data){
               console.log(data)
               console.log('title' in data);
               if('title' in data){
                  document.getElementById('a').value="";
                  todolist('0');

                }
                })
                }
        //待办事项完成
           function is_finish(id){
           fetch('/todos/mark_completed'+'?id='+id)
           .then(res=>res.json())
           .then(function(data){
                if('title' in data){
                todolist('0');
           }
           });
           }
        //删除待办事项
         function del_todo(id){
         title=document.getElementById('del').value
           fetch('/todos/del_todo'+'?title='+title)
           .then(res=>res.json())
           .then(function(data){
                if('title' in data){
                todolist('0')
           }
           });
           }


</script>
  
</html>